package jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCDemo14 {
    public static void main(String[] args) {
        try(Connection conn = DBUtil.getConnection()) {
            //设置事务的隔离级别
            conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
            conn.setAutoCommit(false);  //关闭自动提交
            String sql ="INSERT INTO userinfo(username,password,nickname,age) VALUES(?,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,"李四");
            ps.setString(2,"123456");
            ps.setString(3,"老四");
            ps.setInt(4,18);
            //事务的开启是自动的,当首次执行DML操作,事务就自动开启了
            int count = ps.executeUpdate();   //执行完毕后不会自动提交事务了
            System.out.println(count > 0 ? "添加成功！" : "添加失败！");
//          connection.rollback();//无论执行commit还是rollback,当前事务都结束了
            conn.commit();
            //如果下面又执行新的SQL语句,那么会自动开启一个新的事务
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
